<?php

/**
 * This is the model class for table "{{payacc}}".
 *
 * The followings are the available columns in table '{{payacc}}':
 * @property integer $id
 * @property integer $user_id
 * @property string $work_date
 * @property string $cost
 * @property integer $service_id
 * @property string $comment
 * @property integer $is_active
 * @property string $create_time
 * @property string $update_time
 */
class Payacc extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Payacc the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{payacc}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('user_id, work_date, cost, service_id', 'required'),
			array('user_id, service_id', 'numerical', 'integerOnly'=>true),
			array('work_date', 'validateDate'),
			array('cost', 'validateCost'),
			array('cost', 'numerical'),
			array('comment', 'safe'),
			array('work_date', 'type', 'type'=>'data', 'dateFormat'=>Yii::app()->locale->dateFormat),
			array('is_active', 'boolean'),
			array('create_time, update_time', 'unsafe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, user_id, work_date, cost, service_id, is_active, create_time, update_time, comment', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'service'=>array(self::BELONGS_TO,'Service','service_id',
					'select'=>'id,type',),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => Yii::t('main','Id'),
			'user_id' => Yii::t('main','User'),
			'work_date' => Yii::t('main','Work Date'),
			'cost' => Yii::t('main','Cost'),
			'service_id' => Yii::t('main','Service'),
			'comment' => Yii::t('main','Comment'),
			'is_active' => Yii::t('main','Is Active'),
			'create_time' => Yii::t('main','Create Time'),
			'update_time' => Yii::t('main','Update Time'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria(array('with'=>array('service')));

		$criteria->compare('t.id',$this->id);

		$criteria->compare('t.user_id',$this->user_id);

		$criteria->compare('t.work_date',$this->work_date,true);

		$criteria->compare('t.cost',$this->cost,true);

		$criteria->compare('service.type',$this->service_id);
		
		$criteria->compare('t.comment',$this->comment,true);

		$criteria->compare('t.is_active',$this->is_active);

		$criteria->compare('t.create_time',$this->create_time,true);

		$criteria->compare('t.update_time',$this->update_time,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
			'pagination'=>array('pageSize'=>Setting::get('PerPage')),
			'sort'=>array(
				'defaultOrder'=>'t.work_date DESC',
			),
		));
	}
	
	public function validateCost($attribute,$params)
	{
		if ($this->isNewRecord) {
			return true;
		} else {
			if (!User::model()->canChangeBalance(-($this->oldAttributes[$attribute]-$this->{$attribute}), $this->user_id))
				$this->addError($attribute,'Cannot change sum, balance < 0');
		}
	}
	
	public function validateDate($attribute,$params)
	{
	
	//Yii::trace($this->{$attribute},'app.model.payaac');
		$reddate = new DateTime(date('Y-m-d', CDateTimeParser::parse(Setting::get('RedDate'), Yii::app()->locale->dateFormat)));
		
		if (isset($this->{$attribute})) $date = new DateTime(date('Y-m-d', CDateTimeParser::parse($this->{$attribute}, Yii::app()->locale->dateFormat)));
		if (isset($this->oldAttributes[$attribute])) $olddate = new DateTime(date('Y-m-d', CDateTimeParser::parse($this->oldAttributes[$attribute], Yii::app()->locale->dateFormat)));
		
		if ($date < $reddate || (isset($olddate) && $olddate < $reddate)) {
			$this->addError($attribute,'Date is out of red Date.'.$date->format('Y-m-d H:i:s'));
		}
	}
	
    public function getTotals()		//FIXME сделать статический масив типа
    {
    	$criteria=$this->search()->criteria;
    	$criteria->with='';
    	$criteria->select=new CDbExpression('SUM(cost) as cost');
    	return $this->find($criteria);
    }
    
	public function getTotalCost($begin, $end, $user_id)
	{
		if (!isset($begin)) $begin='0';
		
		if (!isset($end)) {
			$begin = strtotime(date('Y-m-1'));
			$end=strtotime("+1month -1day",$begin);
		}
		
		$sql='select sum(payacc.cost) from yii_payacc as payacc where payacc.is_active=1 and payacc.work_date between :begin and :end and payacc.user_id = :user_id';
		$command = Yii::app()->db->createCommand($sql);
		$command->bindParam(':begin',date('Y-m-d',$begin));
		$command->bindParam(':end',date('Y-m-d',$end));
		$command->bindParam(':user_id',$user_id);
        return sprintf('%.3f', $command->queryScalar());
	}
	
	public function generateAcc($user_id,$date=null)
	{
		global $saveOldAttributes;			// сохранение старых данных бехавиор
		$saveOldAttributes=true;
		
		if (!isset($user_id)) return 0;
		
		if (!isset($date)) $date = time();	// даты начала и конца периода
		$year=date('Y',$date);
		$month=date('m',$date);
		$begin=mktime(0,0,0,$month,1,$year);	//begin
		$end=strtotime("+1month -1day",$begin);	//end
		
		$criteria=new CDbCriteria;
		//$criteria->select='id,service_id,cost,comment,is_active';  // выбираем только нужные поля
		$criteria->condition='user_id=:userID AND work_date between :begin and :end';
		$criteria->params=array(':userID'=>$user_id, ':begin'=>date('Y-m-d',$begin), ':end'=>date('Y-m-d',$end));
		$payaccs=$this->findAll($criteria);		// выбираем все счета за период по пользователю
		
		$services = Service::model()->activeServices($user_id, $date); // все активные услуги пользователя
		
		foreach ($services as $service)
		{
			$is_present = 0;
			$is_change = 0;
			Yii::trace('serch','app.admin.models.payacc');
			foreach ($payaccs as $payacc)
			{
				if ($payacc->service_id == $service->id) {
					if ($payacc->cost != $service->cost) {
						$payacc->cost = $service->cost;
						$is_change = 1;
					}
					if ($payacc->comment != $service->comment) {
						$payacc->comment = $service->comment;
						$is_change = 1;
					}
					if (!$payacc->is_active) {
						$payacc->is_active = 1;
						$is_change = 1;
					}
					//Yii::trace($payacc->work_date,'app.model.payaac');
					
					if ($is_change) $payacc->save();			// сохранение изменений в счете если таковы были
					$is_present = 1;
				}
			}
			if (!$is_present) {					// добавление нового счета если такого небыло
				$newpayacc= new Payacc;
				$newpayacc->cost = $service->cost;
				$newpayacc->comment = $service->comment;
				$newpayacc->work_date = date('d.m.Y', $date);   //FIXME дата учесть преобразования
				$newpayacc->user_id = $user_id;
				$newpayacc->service_id = $service->id;
				
				$newpayacc->save();
				
		//		print(Yii::app()->locale->dateFormat.' '.date(Yii::app()->locale->dateFormat, $date));
				
				foreach ($newpayacc->getErrors() as $er) {
					Yii::trace('save new'.$er,'app.admin.models.payacc');
					//print_r($er);
				}
			}
		}
		
		foreach ($payaccs as $payacc)
		{
			$is_present = 0;
			foreach ($services as $service)
			{
				if ($payacc->service_id == $service->id) {
					$is_present = 1;
				}
			}
			if (!$is_present and $payacc->is_active) {
				$payacc->delete();		//FIXME разобраться с датой окончания действия услуги при сохранении она стает 1700 годом 
			}
		}
		
		//$sql='select * from yii_payacc as payacc where not exists
		//			(select * from yii_service as service where service.id=payacc.service_id and service.is_active = 1 and service.start_date <= payacc.work_date and (service.end_date is null or service.end_date="0000-00-00 00:00:00" or service.end_date >= payacc.work_date))
		//			and payacc.work_date between :begin and :end and payacc.user_id = :user_id';		//FIXME разобраться с датой окончания действия услуги при сохранении она стает 1700 годом 
		//$command = Yii::app()->db->createCommand($sql);
		//$command->bindParam(':begin',date('Y-m-d',$begin));
		//$command->bindParam(':end',date('Y-m-d',$end));
		//$command->bindParam(':user_id',$user_id);
        //$command->execute();						// удаление всех лишних счетов
		
	}
	
	public function behaviors()
    {
        return array(
			'History' => array(
                'class'=>'application.components.behaviors.HistoryBehavior',
            ),
            'DateTime' => array(
				'class'=>'application.components.behaviors.DateTimeBehavior',
			),
			'OldAttributes' => array(
				'class'=>'application.components.behaviors.OldAttributesBehavior',
			),
            'NotActiveOnDelete' => array(
            	'class'=>'application.components.behaviors.NotActiveOnDeleteBehavior',
            ),
        );
    }
    
}